<?php

namespace App\Kuafu\WaiMai\Command;

use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Kuafu\WaiMai\Service\BaseWaiMaiOrderService;
use App\Library\FeiShu\SendFs;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class WaiMaiCheckOrderStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'waimai:check-status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '外卖订单-每日检查订单状态';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command
     *
     * @return int
     */

    private string $errStr = '';

    public function handle()
    {
        $start = strtotime(date('Ymd')) - 86400;

        WaiMaiShopMappingModel::query()
                              ->whereIn('sourceType', [WaiMaiDBEnum::SOURCE_TYPE_MT_WM, WaiMaiDBEnum::SOURCE_TYPE_ELM])
                              ->groupBy('shopId')
                              ->pluck('shopId')
                              ->each(function ($shopId) use ($start) {

                                  WaiMaiOrderModel::suffix($shopId)
                                                  ->where('shopId', $shopId)
                                                  ->whereBetween('createdAt', [$start, $start + 86400 - 1])
                                                  ->whereNotIn('orderStatus',
                                                      [WaiMaiDBEnum::ORDER_STATUS_5, WaiMaiDBEnum::ORDER_STATUS_7])
                                                  ->orderBy('createdAt')
                                                  ->get()
                                                  ->each(function ($item) {

                                                      // 查api的订单状态
                                                      $order = BaseWaiMai::getIns($item->sourceType, $item->shopId)
                                                                         ->getOrderDetail($item->orderId);

                                                      $apiOrderStatus = $order['data']['orderStatus'] ?? null;
                                                      if ($apiOrderStatus == $item->orderStatus) {
                                                          return;
                                                      }

                                                      // 两端[待配送,待制作,配送中] - 不管
                                                      if (in_array($apiOrderStatus, [
                                                              WaiMaiDBEnum::ORDER_STATUS_2,
                                                              WaiMaiDBEnum::ORDER_STATUS_3,
                                                              WaiMaiDBEnum::ORDER_STATUS_4,
                                                          ]) && in_array($item->orderStatus, [
                                                              WaiMaiDBEnum::ORDER_STATUS_2,
                                                              WaiMaiDBEnum::ORDER_STATUS_3,
                                                              WaiMaiDBEnum::ORDER_STATUS_4,
                                                          ])) {
                                                          return;
                                                      }

                                                      // 美团 & DB退单中 & API[待配送,待制作,配送中]
                                                      if ($item->sourceType == WaiMaiDBEnum::SOURCE_TYPE_MT_WM
                                                          && $item->orderStatus == WaiMaiDBEnum::ORDER_STATUS_6
                                                          && in_array($apiOrderStatus,
                                                              [
                                                                  WaiMaiDBEnum::ORDER_STATUS_2,
                                                                  WaiMaiDBEnum::ORDER_STATUS_3,
                                                                  WaiMaiDBEnum::ORDER_STATUS_4,
                                                              ])) {
                                                          return;
                                                      }

                                                      // **状态不相等的情况**
                                                      // 如果api端已完成，直接更新DB就是了
                                                      if ($apiOrderStatus == WaiMaiDBEnum::ORDER_STATUS_5) {
                                                          BaseWaiMaiOrderService::getIns($item->sourceType)
                                                                                ->repairOrderStatus($item->shopId,
                                                                                    $item->orderId);
                                                          Log::channel('waiMai')
                                                             ->info("WaiMaiCheckOrderStatus 直接将订单置为完成 orderID: {$item->orderId} shopId: {$item->shopId}");

                                                          $this->errStr .= "已修复 - shopId:{$item->shopId} orderId:{$item->orderId} DB:{$item->orderStatusText} {$item->createdAt} API:" . (WaiMaiDBEnum::ORDER_STATUS_TEXT[$apiOrderStatus] ?? '') . PHP_EOL;

                                                          return;
                                                      }

                                                      $sourceTypeText  = CodeEnum::SOURCE_TYPES[$item->sourceType] ?? '';
                                                      $orderStatusText = WaiMaiDBEnum::ORDER_STATUS_TEXT[$apiOrderStatus] ?? '';
                                                      $this->errStr    .= "shopId:{$item->shopId} orderId:{$item->orderId} DB:{$item->orderStatusText} {$item->createdAt} API:{$orderStatusText} {$sourceTypeText}" . PHP_EOL;
                                                  });
                              });

        if ($this->errStr) {
            SendFs::newRobot(SendFs::ROBOT_INTERNAL)
                  ->setTitleContent("外卖自查异常", $this->errStr)
                  ->send();
            dump($this->errStr);
        }

        dump('success');
    }
}
